//
// Created by leisurexi on 11/30/20.
// hc_server.c
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 30

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int server_sock, client_sock;
    FILE *fp;
    char buf[BUF_SIZE];
    int read_cnt;

    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;

    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]);
        exit(0);
    }

    fp = fopen("/home/leisurexi/Documents/clion-2020.1.3/Install-Linux-tar.txt", "rb");
    server_sock = socket(AF_INET, SOCK_STREAM, 0);

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr));
    listen(server_sock, 5);

    client_addr_len = sizeof(client_addr);
    client_sock = accept(server_sock, (struct sockaddr *) &client_addr, &client_addr_len);

    while (1) {
        read_cnt = fread((void *) buf, 1, BUF_SIZE, fp);
        if (read_cnt < BUF_SIZE) {
            write(client_sock, buf, read_cnt);
            break;
        }
        write(client_sock, buf, BUF_SIZE);
    }

    shutdown(client_sock, SHUT_WR);
    read_cnt = read(client_sock, buf, BUF_SIZE);
    buf[read_cnt] = 0;
    printf("Message from client: %s \n", buf);

    fclose(fp);
    close(client_sock);
    close(server_sock);
    return 0;
}


